package com.example.demo.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author shenb
 * @date 2022-08-19 11:13
 */
@Component
public class JwtTokenUtil {
    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtil.class);

    private static SignatureAlgorithm SIGNATURE_ALGORITHM = SignatureAlgorithm.HS512;

    private static String PK = "18299B1D459497591B1FDFDF4B656";

    @Autowired
    public void setPK(@Value("${jwt.private.key}") String pk) {
        JwtTokenUtil.PK = pk;
    }

    public static String sign(String username) {
        LocalDateTime now = LocalDateTime.now().plusDays(1);
        Date out = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());

        return Jwts.builder().setSubject(username).setExpiration(out).signWith(SIGNATURE_ALGORITHM, PK).compact();
    }

    public static boolean verity(String token, String username) {
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(PK).parseClaimsJws(token);
            return claimsJws.getBody().getSubject().equals(username);
        } catch (ExpiredJwtException expiredJwtException) {
            log.error("token expired", expiredJwtException);
            return false;
        } catch (Exception e) {
            log.error("Token parse error", e);
            return false;
        }
    }

    public static String verity(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(PK).parseClaimsJws(token);
        return claimsJws.getBody().getSubject();
    }
}

